﻿using System;
using System.Linq;
using System.Web.Mvc;
using Icms.Core;
using Icms.Core.Model;
using Icms.Core.Repository;
using Icms.Core.Service;
using Icms.WebUI.Builder;
using Icms.WebUI.Dto;
using Omu.Awesome.Mvc;

namespace Icms.WebUI.Controllers
{
    [Authorize(Roles="admin,user")]
    public class ReportRequestController : BaseController
    {
        private readonly IRepo<ReportRequest> repo;
        private readonly IMapper<ReportRequest, ReportRequestInput> mapper;
        private readonly IReportService reportService;
        private readonly IUserService userService;

        public ReportRequestController(IRepo<ReportRequest> repo, IMapper<ReportRequest, ReportRequestInput> mapper, IReportService reportService, IUserService userService)
        {
            this.repo = repo;
            this.userService = userService;
            this.reportService = reportService;
            this.mapper = mapper;
        }

        public ActionResult Create()
        {
            return View(new ReportRequestInput());
        }

        [HttpPost]
        public ActionResult Create(ReportRequestInput input)
        {
            if (!ModelState.IsValid) return View(input);
            var entity = mapper.MapToEntity(input);
            return Json(new { Id = reportService.Create(entity, Globals.User().Id) });
        }

        public virtual ActionResult Search(string search, int? ReportTemplateGroup, DateTime? dateFrom, DateTime? dateTo, int page = 1, int ps = 5)
        {
            search = search.ToLower();
            var userId = Globals.User().Id;
            var src = repo.Where(o => true);

            var items = src
                .Where(o => o.UserId == userId && o.ReportTemplate != null
                    && (ReportTemplateGroup == null || ReportTemplateGroup == o.ReportTemplate.GroupId)
                    && (dateFrom == null || o.Date.Date >= dateFrom)
                    && (dateTo == null || o.Date.Date <= dateTo)
                    && o.ReportTemplate.Title.ToLower().Contains(search))
                .OrderByDescending(u => u.Date);

            var rows = this.RenderView("rows", items.Pag(page, ps));

            return Json(new { rows, more = items.Count() > page * ps });
        }

        public virtual ActionResult Index()
        {
            return View("cruds");
        }

        public virtual ActionResult Row(Guid id)
        {
            return View("rows", new[] { repo.Get(id) });
        }

        public ActionResult Download(Guid id)
        {
            return File(reportService.GetFilePath(id), "application/ms-excel", repo.Get(id).ReportTemplate.Name + repo.Get(id).Date + ".xls");
        }
    }
}